package com.uziot.distributed.uaa.web;

import com.alibaba.fastjson.JSON;
import com.uziot.distributed.uaa.service.UaaJdbcClientDetailsServiceImpl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shidt
 * @version V1.0
 * @className MyLoginController
 * @date 2020-08-24 22:21:50
 * @description
 */
@Slf4j
@Controller
public class UaaLoginController {

    @Autowired
    private TokenEndpoint tokenEndpoint;
    @Autowired
    private UaaJdbcClientDetailsServiceImpl uaaJdbcClientDetailsService;

    /**
     * 指定自定义授权码模式登陆跳转地址
     *
     * @return 视图地址
     */
    @RequestMapping("/custom/login")
    public String hello() {
        return "login";
    }

    /**
     * 自定义授权确认页面
     *
     * @param request 请求
     * @param model   视图
     * @return 视图地址
     */
    @RequestMapping("/custom/confirm_access")
    public String getAccessConfirmation(HttpServletRequest request, Model model) {
        String clientId = request.getParameter("client_id");
        String scope = request.getParameter("scope");
        model.addAttribute("scopes", scope);
        ClientDetails client = uaaJdbcClientDetailsService.loadClientByClientId(clientId);
        model.addAttribute("client", client);

        return "grant";
    }

    @PostMapping(value = "/my/login")
    @ResponseBody
    public Object login(@RequestBody UserVo user, HttpServletRequest request) throws Exception {
        log.info("登陆信息为：{}", JSON.toJSONString(user));

        Map<String, String> params = new HashMap<>(6);
        params.put("username", user.getUsername());
        params.put("password", user.getPassword());
        params.put("code", user.getCode());
        params.put("client_id", user.getClientId());
        params.put("client_secret", user.getClientSecret());
        params.put("grant_type", user.getGrantType());


        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(user.getClientId(), null, null);
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

        ResponseEntity<OAuth2AccessToken> responseEntity = tokenEndpoint.postAccessToken(authenticationToken, params);
        OAuth2AccessToken auth2AccessToken = responseEntity.getBody();
        log.info("用户登陆响应结果为：{}", JSON.toJSONString(auth2AccessToken));
        return responseEntity;

    }

    @Data
    public static class UserVo {
        private String username;
        private String password;
        private String code;
        private String clientId = "c1";
        private String clientSecret = "secret";
        private String grantType = "password";
    }


}
